package com.yupi.mianshiya.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.mianshiya.common.BaseResponse;
import com.yupi.mianshiya.common.DeleteRequest;
import com.yupi.mianshiya.common.ErrorCode;
import com.yupi.mianshiya.common.ResultUtils;
import com.yupi.mianshiya.constant.UserConstant;
import com.yupi.mianshiya.exception.BusinessException;
import com.yupi.mianshiya.exception.ThrowUtils;
import com.yupi.mianshiya.model.dto.articles.ArticleQueryRequest;
import com.yupi.mianshiya.model.dto.articles.ArticlesAddRequest;
import com.yupi.mianshiya.model.dto.articles.ArticlesEditRequest;
import com.yupi.mianshiya.model.dto.questionBank.QuestionBankAddRequest;
import com.yupi.mianshiya.model.entity.Articles;
import com.yupi.mianshiya.model.entity.Question;
import com.yupi.mianshiya.model.entity.QuestionBank;
import com.yupi.mianshiya.model.entity.User;
import com.yupi.mianshiya.model.vo.ArticleVO;
import com.yupi.mianshiya.model.vo.ArticlesVO;
import com.yupi.mianshiya.service.ArticlesService;
import com.yupi.mianshiya.service.FavoriteService;
import com.yupi.mianshiya.service.UserService;
import com.yupi.mianshiya.utils.QiniuKodoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticlesController {

    @Resource
    private FavoriteService favoriteService;

    @Autowired
    private UserService userService;

    @Resource
    private ArticlesService articlesService;

    @Resource
    private QiniuKodoUtil qiniuKodoUtil;

    @ApiOperation("上传文章图片")
    @PostMapping("/upload")
    public BaseResponse<String> uploadArticleImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            String fileKey  = qiniuKodoUtil.upload(file, "articleimages");
            if (fileKey == null) {
                throw new BusinessException( ErrorCode.SYSTEM_ERROR, "上传失败");
            }
            // 获取可访问的 URL
            String fileUrl = qiniuKodoUtil.getFileUrl(fileKey);
            return ResultUtils.success(fileUrl);
        }
        catch (Exception  e) {
            log.error("上传图片失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "上传图片失败");

        }
    }

    @ApiOperation("新增文章")
    @PostMapping("/add")
    public BaseResponse<Long> addArticle(@RequestBody ArticlesAddRequest articlesAddRequest, HttpServletRequest request) {
        // 校验参数
        if (StringUtils.isBlank(articlesAddRequest.getTitle())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(articlesAddRequest.getContent())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        Articles articles = new Articles();
        List<String> tags = articlesAddRequest.getTags();
        if (tags != null) {
            articles.setTags(JSONUtil.toJsonStr(tags));
        }


        articles.setUserId(userService.getLoginUser(request).getId());
        BeanUtils.copyProperties(articlesAddRequest, articles);
        // 保存文章
        articlesService.save(articles);
        return ResultUtils.success(articles.getId());

    }

    @ApiOperation("删除文章")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteArticle(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 校验参数
        if (deleteRequest.getId() == null || deleteRequest.getId() <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }


        articlesService.deleteArticle(deleteRequest, request);



        return ResultUtils.success(true);

    }

    @ApiOperation("修改文章")
    @PostMapping("/edit")
    public BaseResponse<Boolean> editArticle(@RequestBody ArticlesEditRequest articlesEditRequest, HttpServletRequest request) {
        // 校验参数
        if (StringUtils.isBlank(articlesEditRequest.getTitle())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(articlesEditRequest.getContent())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        if (articlesEditRequest.getId() == null || articlesEditRequest.getId() <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        long articleId = articlesEditRequest.getId();
        // 获取登录用户的id
        Long userid = userService.getLoginUser(request).getId();
        Articles articles = articlesService.getById(articleId);
        Long articleUserId = articles.getUserId();
        BeanUtils.copyProperties(articlesEditRequest, articles);
        List<String> tags = articlesEditRequest.getTags();
        if (tags != null) {
            articles.setTags(JSONUtil.toJsonStr(tags));
        }
        //仅本人才能修改
        if(userid.equals(articleUserId)) {
            // 修改文章
            boolean result = articlesService.updateById(articles);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            return ResultUtils.success(result);
        }

        return ResultUtils.error(ErrorCode.NO_AUTH_ERROR);
    }


    @ApiOperation("查询文章-管理员用")
    @PostMapping("/list")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Articles>> listArticles(@RequestBody ArticleQueryRequest articleQueryRequest, HttpServletRequest request) {

        // 校验参数
        ThrowUtils.throwIf(articleQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = articleQueryRequest.getCurrent();
        int size = articleQueryRequest.getPageSize();
        //判断是否是管理员
        boolean isAdmin = userService.isAdmin(request);
        // 如果不是管理员，而查太多直接抛异常
        if (!isAdmin && size > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 查询数据库
        Page<Articles> questionPage = articlesService.page(new Page<>(current, size),
                articlesService.getQueryWrapper(articleQueryRequest));


        return ResultUtils.success(questionPage);
    }

    @ApiOperation("查询文章-不返回文章内容")
    @PostMapping("/list/vo")
    public BaseResponse<Page<ArticlesVO>> listArticlesVo(@RequestBody ArticleQueryRequest articleQueryRequest, HttpServletRequest request) {
        //登录用户
        User loginUser = userService.getLoginUser(request);
        // 校验参数
        ThrowUtils.throwIf(articleQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = articleQueryRequest.getCurrent();
        int size = articleQueryRequest.getPageSize();
        //判断是否是管理员
        boolean isAdmin = userService.isAdmin(request);
        // 如果不是管理员，而查太多直接抛异常
        if (!isAdmin && size > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 查询数据库
        Page<Articles> questionPage = articlesService.page(new Page<>(current, size),
                articlesService.getQueryWrapper(articleQueryRequest));
        //转换成vo
        List<ArticlesVO> articlesVOList = articlesService.convertArticlesToVO(questionPage.getRecords());
        //设置作者名称
        for (ArticlesVO articlesVO : articlesVOList) {
            User user = userService.getById(articlesVO.getUserId());
            articlesVO.setUsername(user.getUserName());
        }
        Page<ArticlesVO> articlesVOPage = new Page<>();
        BeanUtils.copyProperties(questionPage, articlesVOPage);
        articlesVOPage.setRecords(articlesVOList);
        //返回
        return ResultUtils.success(articlesVOPage);



    }


    /**
     * 多加了作者名称
     * @param id
     * @param request
     * @return
     */
    @ApiOperation("根据id拿到文章")
    @GetMapping("/get")
    public BaseResponse<ArticleVO> getArticleById(long id, HttpServletRequest request) {
        // 校验参数
        if (id <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        // 获取登录用户的id
        userService.getLoginUser(request).getId();
        ArticleVO articleVO = new ArticleVO();

        // 查询文章
        Articles articles = articlesService.getById(id);
        BeanUtils.copyProperties(articles, articleVO);
        // 查询作者
        User user = userService.getById(articles.getUserId());
        articleVO.setUsername(user.getUserName());
        // 返回文章
        return ResultUtils.success(articleVO);
    }



}
